package com.baitengsoft.patentservicemonitor.job.task;

import com.aliyun.oss.common.utils.IOUtils;
import com.baitengsoft.patentservicemonitor.common.utils.DateUtils;
import com.baitengsoft.patentservicemonitor.job.model.PatentUpdateSearchParam;
import com.baitengsoft.patentservicemonitor.job.service.ScheduleJobService;
import com.baitengsoft.patentservicemonitor.job.utils.HttpUtils;
import com.baitengsoft.patentservicemonitor.job.utils.SysParametersUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.xml.bind.DatatypeConverter;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 测试定时任务(演示Demo，可删除)
 * <p>
 * testTask为spring bean的名称
 *
 * @author KennyGu
 * @email 89335272@qq.com
 * @date 2016年11月30日 下午1:34:24
 */
@Component("patentSynchroTask")
public class PatentSynchroTask {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    private static final String INIT_FIELDS = "an,ti,class,lsnt,ad,apd,cagc,in1,pa1,cpa1,caa,paa,sed,aic1,lsn2,pd,ivd,tfd,ic1,ppa1,aa,cdn,pdn";
    @Autowired
    private ScheduleJobService scheduleJobService;
    @Autowired
    private SysParametersUtil sysParametersUtil;
    /**
     * @Author: KennyGu
     * @Date: 2018/1/16
     * @Description: 添加平台时的初始化数据-只使用一次--添加平台时
     */
//    public void JobFastInitData(String params) {
//        logger.info("我是带参数的JobInitData方法，正在被执行，参数为：" + params);
//        String inpatstr = "?query=" + params + "&folder=99-10&call_back=http://www.baidu.com&fields=an,ti,class,lsnt,ad,apd,cagc,in1,pa1,cpa1,caa,paa,ased,aic1,lsn2,pd,ivd,tfd,ic1,ppa1,aa";
//        try {
//            excuteurlget(sysParametersUtil.getInitDataUrl() + inpatstr);
//        } catch (Exception ex) {
//            logger.error(ex.getMessage(), ex);
//
//        }
//
//    }

    /**
     * @Author: KennyGu
     * @Date: 2018/1/16
     * @Description: 添加平台时的初始化数据
     */
    public void JobInitData(String params, String folder) {
        logger.info("我是带参数的JobInitData方法，正在被执行，参数为：" + params);
        Map<String, Object> map = new HashMap<>();
        map.put("query", params);
        map.put("folder", folder);
        map.put("call_back", sysParametersUtil.getInitDataCallbackUrl());
        map.put("fields", INIT_FIELDS);
        try {
            excuteurlget(sysParametersUtil.getInitDataUrl() + HttpUtils.getUrl(map));
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            throw new RuntimeException(ex);
        }

    }

    /**
     * @Author: KennyGu
     * @Date: 2018/1/16
     * @Description: 添加平台时的初始化数据
     */
    public void jobInitOutData(String params, String folder) {
        logger.info("我是带参数的JobInitData方法，正在被执行，参数为：" + params);

        try {
            Map<String, Object> map = new HashMap<>();
            map.put("query", params.replace("cdn", "pdn") + URLEncoder.encode(" and not  ", "UTF-8") + params);
            map.put("folder", folder + "-out");
            map.put("call_back", sysParametersUtil.getInitOutDataCallbackUrl());
            map.put("fields", INIT_FIELDS);
            excuteurlget(sysParametersUtil.getInitDataUrl() + HttpUtils.getUrl(map));
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            throw new RuntimeException(ex);
        }
    }


    /**
     * 批量更新数据
     *
     * @param queryParam
     * @param folder
     */
    public void updateMonthData(String queryParam, String folder) {
        String batch = String.valueOf(DateUtils.getYear(new Date())) + DateUtils.getMonthStr(new Date());
        folder = folder + "/" + String.valueOf(DateUtils.getYear(new Date())) + "/" + String.valueOf(DateUtils.getMonth(new Date()));

        if (queryParam.toLowerCase().indexOf("cdn:") != -1) {
            queryParam = queryParam.replace("cdn:", "").trim();
        }
        PatentUpdateSearchParam param = new PatentUpdateSearchParam(PatentUpdateSearchParam.QueryTypeEnum.CDN, queryParam, batch, sysParametersUtil.getInitUpdateDataCallbackUrl(), folder);
        try {
            excuteurlget(sysParametersUtil.getInitUpdateDataUrl() + "?" + param.getUrlParam());
        } catch (UnsupportedEncodingException exception) {
            logger.error(exception.getMessage(), exception);

        } catch (IOException exception) {
            logger.error(exception.getMessage(), exception);

        }
    }

    /**
     * 批量更新数据
     */
    public void updateData(String queryParam, String folder) {
        String batch = String.valueOf(DateUtils.getYear(new Date())) + DateUtils.getMonthStr(new Date());
        folder = folder + "/" + String.valueOf(DateUtils.getYear(new Date())) + "/" + String.valueOf(DateUtils.getMonth(new Date()));
        PatentUpdateSearchParam.QueryTypeEnum queryTypeEnum = null;

        //判断传入检索式类型

        if (queryParam.toLowerCase().indexOf(PatentUpdateSearchParam.QueryTypeEnum.CDN.getValue() + ":") != -1) {
            queryParam = queryParam.replace(PatentUpdateSearchParam.QueryTypeEnum.CDN.getValue() + ":", "").trim();
            queryTypeEnum = PatentUpdateSearchParam.QueryTypeEnum.CDN;
        } else if (queryParam.toLowerCase().indexOf(PatentUpdateSearchParam.QueryTypeEnum.AN.getValue() + ":") != -1) {
            queryParam = queryParam.replace(PatentUpdateSearchParam.QueryTypeEnum.AN.getValue() + ":", "").trim();
            queryTypeEnum = PatentUpdateSearchParam.QueryTypeEnum.AN;

        } else if (queryParam.toLowerCase().indexOf(PatentUpdateSearchParam.QueryTypeEnum.PA.getValue() + ":") != -1) {
            queryParam = queryParam.replace(PatentUpdateSearchParam.QueryTypeEnum.PA.getValue() + ":", "").trim();
            queryTypeEnum = PatentUpdateSearchParam.QueryTypeEnum.PA;
        }

        if (queryTypeEnum == null) {
            throw new RuntimeException("当前检索式不正确");
        }
        PatentUpdateSearchParam param = new PatentUpdateSearchParam(queryTypeEnum, queryParam, batch, sysParametersUtil.getInitUpdateDataCallbackUrl(), folder);
        try {
            excuteurlget(sysParametersUtil.getInitUpdateDataUrl() + "?" + param.getUrlParam());
        } catch (UnsupportedEncodingException exception) {
            System.out.println(exception);
        } catch (IOException exception) {
            System.out.println(exception);
        }

    }


    public static void main(String[] args) {

        // PatentSynchroTask task = new PatentSynchroTask();
        //task.updateData();
        //task.JobInitData("cdn:江苏省/常州市/武进区");

        //task.JobInitOutData("cdn:江苏省/常州市/武进区");


        System.out.println(DateUtils.getMonth(new Date()));
    }


    /**
     * 通过httpClient方式调用kylin Restful接口
     *
     * @param method
     * @param params
     * @return
     */
    public StringBuffer excute(String stringurl, String method, String params) {
        StringBuffer out = new StringBuffer();
        try {
            URL url = new URL(stringurl);
            System.out.println(url);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod(method);
            connection.setDoOutput(true);
            //connection.setRequestProperty("Authorization", "Basic " + encoding);
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            if (params != null) {
                byte[] outputInBytes = params.getBytes("UTF-8");
                OutputStream os = connection.getOutputStream();
                os.write(outputInBytes);
                os.close();
            }
            InputStream content = connection.getInputStream();
            // 解决乱码问题
            BufferedReader in = new BufferedReader(new InputStreamReader(content, Charset.forName("UTF-8")));
            String line;
            while ((line = in.readLine()) != null) {
                out.append(line);
            }
            in.close();
            connection.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return out;
    }

    /**
     * 通过httpClient方式---方法二
     *
     * @param path
     * @return
     */
    private void excuteurlget(String path) throws ClientProtocolException, IOException {
        //认证信息对象，用于包含访问翻译服务的用户名和密码

        //String path = "http://************";
        //1.创建客户端访问服务器的httpclient对象   打开浏览器
        HttpClient httpclient = new DefaultHttpClient();
        //2.以请求的连接地址创建get请求对象     浏览器中输入网址

        System.out.println(path);
        HttpGet httpget = new HttpGet(path);

        //username:password--->访问的用户名，密码,并使用base64进行加密，将加密的字节信息转化为string类型，encoding--->token
        String encoding = DatatypeConverter.printBase64Binary("username:password".getBytes("UTF-8"));

        httpget.setHeader("Authorization", "Basic " + encoding);
        //3.向服务器端发送请求 并且获取响应对象  浏览器中输入网址点击回车
        HttpResponse response = httpclient.execute(httpget);
        //4.获取响应对象中的响应码
        StatusLine statusLine = response.getStatusLine();//获取请求对象中的响应行对象
        int responseCode = statusLine.getStatusCode();//从状态行中获取状态码

        System.out.println(responseCode);
        if (responseCode == 200) {
            //5.  可以接收和发送消息
            HttpEntity entity = response.getEntity();
            //6.从消息载体对象中获取操作的读取流对象
//            InputStream input = entity.getContent();
//            BufferedReader br = new BufferedReader(new InputStreamReader(input));
            String result = IOUtils.readStreamAsString(response.getEntity().getContent(), "UTF-8");
            //br.readLine();
            //String result = new String(str1.getBytes("gbk"), "utf-8");
            System.out.println("服务器的响应是:" + result);
//            br.close();
//            input.close();
        } else {
            System.out.println("响应失败!");

            //TODO 日志记录
        }

    }
}
